package com.noranj.web.client;

import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.noranj.web.shared.UserAccountDTO;
import com.sun.java.swing.plaf.windows.resources.windows;

public class HeaderPanel extends Composite {

	private static HeaderPanelUiBinder uiBinder = GWT
			.create(HeaderPanelUiBinder.class);

	interface HeaderPanelUiBinder extends UiBinder<Widget, HeaderPanel> {
	} 
		
	@UiField
	Anchor logoutLink;
	
	@UiField
	Label nickName;

    @UiHandler("logoutLink")
    void onLogoutClick(ClickEvent e) {
    	  doLogout();
      }
    
	private List<UserAccountDTO> userAccountDTO;
	
	private final UserManagmentAsync userManagment = GWT.create(UserManagment.class); 
	
	public HeaderPanel() {
		initWidget(uiBinder.createAndBindUi(this));
		getUserAccountDTO();
	}
	 	
	protected void showUserAccountInfo(List<UserAccountDTO> userAccountDTO) {
	    setUserAccountDTO(userAccountDTO);
	}

	private void setUserAccountDTO(List<UserAccountDTO> userAccountDTO){
		if(userAccountDTO!= null)
			nickName.setText(userAccountDTO.get(0).getName().toString());
		else 
			nickName.setText("tset@test.com");
	}
	
	private void getUserAccountDTO(){
		userManagment.userAccountInfo( new AsyncCallback<List<UserAccountDTO>>() {
		      public void onFailure(Throwable caught) {
		        //Window.alert("An error occurred");
		      }

			@Override
			public void onSuccess(List<UserAccountDTO> result) {
				showUserAccountInfo(result);
				
			}
		    });
	 }
	
	private void doLogout() {
		userManagment.logout("../default.html", new AsyncCallback<String>() {

			@Override
			public void onFailure(Throwable caught) {
				Window.alert("An error occurred");
				
			}

			@Override
			public void onSuccess(String result) {
				Window.Location.replace(result);
			}
	        
	      });
	}
}